﻿using AutoMapper;
using MediatR;
using SC.GirdManage.Common;
using SC.GirdManage.Repository;
using SC.GridManage.API.Write.Application.Command.UnitGrid;
using SC.GridManage.Domain.Models;

namespace SC.GridManage.API.Write.Application.Handler.UnitGrid
{
    public class UpdateUnitGridHandler : IRequestHandler<UpdateUnitGridCommond, ApiResult<int>>
    {
        private readonly IBaseRepository<UnitGridModel> unitGridRepo;
        private readonly IMapper mapper;

        public UpdateUnitGridHandler(IBaseRepository<UnitGridModel> unitGridRepo,IMapper mapper)
        {
            this.unitGridRepo = unitGridRepo;
            this.mapper = mapper;
        }

        public Task<ApiResult<int>> Handle(UpdateUnitGridCommond request, CancellationToken cancellationToken)
        {
 
                ApiResult<int> result = new ApiResult<int>();

                //查询数据库中是否已有GridNo 网格编号
                var count = unitGridRepo.QueryAsync(x => x.GridNo == request.GridNo&&x.Id!=request.Id).Result.Count();

            if (count >= 1)
            {
                result.Data = count;
                result.Msg = "单元网格编号已经存在.";
                result.Code = GirdManage.Common.Enums.EnumResultCode.Error;
                return Task.FromResult(result);
            }

            var updateModel = mapper.Map<UnitGridModel>(request);
            int r =  unitGridRepo.UpdateAsync(updateModel).Result;
            if (r > 0)
            {
                result.Data = r;
                result.Msg = "单元网格更新成功.";
                result.Code = GirdManage.Common.Enums.EnumResultCode.Success;
            }
            else
            {
                result.Data = r;
                result.Msg = "单元网格更新失败.";
                result.Code = GirdManage.Common.Enums.EnumResultCode.Fail;
            }
            return Task.FromResult(result);
        }
    }
}
